﻿var file_collection = new Array();
var index = 0;
var data = new FormData();

function selectAttachments() {
    // alert("Total files = "+  file_collection.length);

    var items = document.getElementById("list_files").childNodes;

    for (var i = 0; i < items.length; i++) {
        var ch = items[i].firstChild;
        if (ch.checked) {
            alert(file_collection[i][0] + i);
            data.append(file_collection[i][0], file_collection[i][1]);
        }

    }

    $.ajax({
        type: "POST",
        url: "Controller.ashx",
        contentType: false,
        processData: false,
        data: data,
        success: function (result) {
            alert(result);
        },
        error: function () {
            alert("There was error uploading files!");
        }
    });
}

function s1() {

    $('#box').bind('dragenter', ignoreDrag)
    .bind('dragover', ignoreDrag)
    .bind('drop', drop);
    alert("after event");
}

/*
function drop(e) {
    //alert('dopr called');
    ignoreDrag(e);
    //$("#box").show();
    $("#abc").show();
    var dt = e.originalEvent.dataTransfer;
    var files = dt.files;
    alert(dt.files.length + " Files uploaded");

    for (var x = 0; x < dt.files.length; x++) {
        var item = document.createElement("li");
        item.setAttribute('style', 'list-style-type: none');
        var c = document.createElement("input");
        c.setAttribute('type', 'checkbox');
        c.setAttribute('checked', 'checked');
        item.appendChild(c);
        var t = document.createTextNode(dt.files[x].name);
        item.appendChild(t);
        document.getElementById('list_files').appendChild(item);

        //loading the array
        file_collection[index] = new Array(2);
        file_collection[index][0] = dt.files[x].name;
        file_collection[index][1] = dt.files[x];
        index++;
        // alert("saved = " + file_collection[index, 0] + "----->" +file_collection[index, 1] + " ---- " + index);


    }

}


function ignoreDrag(e) {
    e.originalEvent.stopPropagation();
    e.originalEvent.preventDefault();
}
*/
function load_lst() {

    $("#abc").show();

    var input = document.getElementById('myfile');

    for (var x = 0; x < input.files.length; x++) {
        var item = document.createElement("li");
        item.setAttribute('style', 'list-style-type: none');
        var c = document.createElement("input");
        c.setAttribute('type', 'checkbox');
        c.setAttribute('checked', 'checked');
        item.appendChild(c);
        var t = document.createTextNode(input.files[x].name);
        item.appendChild(t);
        document.getElementById('list_files').appendChild(item);

        //loading the array
        file_collection[index] = new Array(2);
        file_collection[index][0] = input.files[x].name;
        file_collection[index][1] = input.files[x];
        index++;
        //     alert("saved = " + file_collection[index, 0] +"------>"+ file_collection[index, 1]);

    }


}

// ------------------ End of File Uploading code ----------------------------

function ProcessAjax(url) {

    var XMLHttpRequestObj = new XMLHttpRequest();

    XMLHttpRequestObj.open("Get", url, true);
    XMLHttpRequestObj.send();
    XMLHttpRequestObj.onreadystatechange = function () {
        if (XMLHttpRequestObj.readyState == 4) {
            document.getElementById("Contents").innerHTML = XMLHttpRequestObj.responseText;
        }
    }
}

/*old initiate circulation
function InitiateCirculation() {

    ProcessAjax("./Controller.ashx?action=InitiateCirculation&documentId=" + document.getElementById("selectedForm").value);
    //s1();
    bindEvents();
}
*/
function GenerateTemplate() {

    ProcessAjax("./Controller.ashx?action=ViewFormTemplate");
}

function ViewCirculationDetails() {

    ProcessAjax("./Controller.ashx?action=ViewDetails");

    s1();
}

function EditCirculationDetails() {

    ProcessAjax("./Controller.ashx?action=EditDetails");
    alert('in EditCirculation');
    s1();
}

function SaveUserProfile() {

    var url = "./Controller.ashx?action=SaveUserProfile";
    var XMLHttpRequestObj = new XMLHttpRequest();

    XMLHttpRequestObj.open("Get", url, true);
    XMLHttpRequestObj.send();
    XMLHttpRequestObj.onreadystatechange = function () {
        //alert("after XMLHttpRequestObj.onreadystatechange");
        if (XMLHttpRequestObj.readyState == 4) {
            //alert("after state 4");
            var formHtml = "";
            var serializedHtmlFieldIdList = XMLHttpRequestObj.responseText;
            var parsedHtmlFieldIdList = JSON.parse(serializedHtmlFieldIdList);
            var fieldValues = new Array();

            for (var j = 0; j < parsedHtmlFieldIdList.length; j++) {
                if (document.getElementById(parsedHtmlFieldIdList[j]).value == "") {
                    alert("Please provide complete information!");
                    document.getElementById(parsedHtmlFieldIdList[j]).focus();
                    return;
                }
            }

            for (var i = 0; i < parsedHtmlFieldIdList.length; i++) {
                //alert("first tym lop");
                fieldValues[i] = document.getElementById(parsedHtmlFieldIdList[i]).value;
                //alert("inloop" + fieldValues[i]);
            }
            //alert("after3");
            var testVar = JSON.stringify(fieldValues);
            //alert("after4");
            ProcessAjax("./Controller.ashx?action=SaveProfileSectionValues&jsonText=" + JSON.stringify(fieldValues) + "&jsonText2=" + JSON.stringify(parsedHtmlFieldIdList));
        }
    }


}


function SaveSectionValues() {

    selectAttachments();

    var url = "./Controller.ashx?action=GetFieldIdList";

    var XMLHttpRequestObj = new XMLHttpRequest();

    XMLHttpRequestObj.open("Get", url, true);
    XMLHttpRequestObj.send();
    XMLHttpRequestObj.onreadystatechange = function () {
        //alert("after XMLHttpRequestObj.onreadystatechange");
        if (XMLHttpRequestObj.readyState == 4) {

            var formHtml = "";
            var serializedHtmlFieldIdList = XMLHttpRequestObj.responseText;
            var parsedHtmlFieldIdList = JSON.parse(serializedHtmlFieldIdList);
            var fieldValues = new Array();

            for (var j = 0; j < parsedHtmlFieldIdList.length; j++) {
                if (document.getElementById(parsedHtmlFieldIdList[j]).value == "") {
                    alert("Please provide complete information!");
                    document.getElementById(parsedHtmlFieldIdList[j]).focus();
                    return;
                }
            }


            for (var i = 0; i < parsedHtmlFieldIdList.length; i++) {


                //alert("in non empty function");
                // if (parsedHtmlFieldIdList[i].lastIndexOf("RB") == (parsedHtmlFieldIdList[i].length - 2)) // Radio Button
                // {
                //     var radioButtonOptions = document.getElementsByName(parsedHtmlFieldIdList[i]);
                //
                //    for (var k = 0; k < radioButtonOptions.length; k++)
                //        if (radioButtonOptions[k].checked == true)
                //           fieldValues[i] = radioButtonOptions[k].value;
                // }
                //else {
                fieldValues[i] = document.getElementById(parsedHtmlFieldIdList[i]).value;
                //}
            }

           // alert("before sav section vlues");
            var testVar = JSON.stringify(fieldValues);
            ProcessAjax("./Controller.ashx?action=SaveSectionValues&jsonText=" + JSON.stringify(fieldValues));
        }
    }
}

function getPrint(circulationId) {

    var XMLHttpRequestObj = new XMLHttpRequest();

    XMLHttpRequestObj.open("Get", "./Controller.ashx?action=GeneratePrintPreview&circulationId=" + circulationId, true);
    XMLHttpRequestObj.send();
    XMLHttpRequestObj.onreadystatechange = function () {
        if (XMLHttpRequestObj.readyState == 4) {
            var printPreview = window.open();
            printPreview.document.writeln(XMLHttpRequestObj.responseText);
        }
    }
}

//Additions
function loadCirculationList() {
    $('#ciculationlistz').append('<div>table goes here</div>');
    var parsedHtmlFieldIdList = '';
    var response = '';

    $.ajax({
        type: "Get",
        url: "Controller.ashx?action=GetInitiatedForms",
        contentType: false,
        processData: false,
        success: function (result) {
            alert(result);
            reponse = result;
            $('#formtypes').html(result);
        },
        error: function (xhr, err) {
            alert("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
            alert("responseText: " + xhr.responseText);
            console.log(xhr.responseText);
        }
    });
}

//loading document in dropdown on initiating circulation
function LoadDocumentsInDropDown() {

    $.ajax({
        type: "Get",
        url: "Controller.ashx?action=GetDocumentsList",
        contentType: false,
        processData: false,
        success: function (result) {

            $('#DropDownListContents').html(result);
        },
        error: function (xhr, err) {
            alert("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
            alert("responseText: " + xhr.responseText);
            console.log(xhr.responseText);
        }
    });

}

//loading initaite circulation page
function loadFormTypePages() {
    $("#Contents").load("InitiateCirculation.aspx");
    LoadDocumentsInDropDown();
}

function SpecifyLeftPanel() {
    $.ajax({
        type: "Get",
        url: "Controller.ashx?action=GetLeftPanelContents",
        contentType: false,
        processData: false,
        success: function (result) {

            document.getElementById("leftPanel").innerHTML = result; ;

        },
        error: function (xhr, err) {
            alert("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
            alert("responseText: " + xhr.responseText);
            console.log(xhr.responseText);
        }
    });
}

function loadViewCirculationList() {
    //alert("vc");
    $.ajax({
        type: "Get",
        url: "Controller.ashx?action=GetRoleFromSession",
        contentType: false,
        processData: false,
        success: function (result) {
            alert(result);
            $("#con").load(result);
            //alert("before load");
            LoadDocumentsInDropDown();
            SpecifyLeftPanel();
        },
        error: function (xhr, err) {
            alert("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
            alert("responseText: " + xhr.responseText);
            console.log(xhr.responseText);
        }
    });

}

function LoadContents() {
    //alert("loading contents");
    $.ajax({
        type: "Get",
        url: "Controller.ashx?action=ViewCirculationList",
        contentType: false,
        processData: false,
        success: function (result) {
   //         alert(result);
            $("#vList").append(result);

            var rows = $('table').find('tbody tr').length;
           // alert("Rows -- " + rows);

            var no_rec_per_page = 4;
            var no_pages = Math.ceil(rows / no_rec_per_page);
            var $pagenumbers = $('<div id="pages"></div>');
            for (i = 0; i < no_pages; i++) {
                $('<span style ="margin:5px">' + (i + 1) + '</span>').appendTo($pagenumbers);
            }
            $pagenumbers.insertAfter('table');
            $('.page').hover(
            function () {
                $(this).addClass('hover');
            },
            function () {
                $(this).removeClass('hover');
            }
        );
            $('table').find('tbody tr').hide();
            var tr = $('table tbody tr');
            for (var i = 0; i <= no_rec_per_page - 1; i++) {
                $(tr[i]).show();
            }
            $('span').click(function (event) {
                $('table').find('tbody tr').hide();
                for (i = ($(this).text() - 1) * no_rec_per_page; i <= $(this).text() * no_rec_per_page - 1; i++) {
                    $(tr[i]).show();
                }
            });

            


        },
        error: function (xhr, err) {
            alert("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
            alert("responseText: " + xhr.responseText);
            console.log(xhr.responseText);
        }
    });
}

// load view circulation details
function loadViewCirculationDetails(id) {
    //alert("loading circ details");
    $.ajax({
        type: "Get",
        url: "Controller.ashx?action=GetFormDetails&cId=" + id,
        contentType: false,
        processData: false,
        success: function (result) {
            alert(result);
            document.getElementById("con").innerHTML = result;
        },
        error: function (xhr, err) {
            alert("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
            alert("responseText: " + xhr.responseText);
            console.log(xhr.responseText);
        }
    });
}


function InitiateCirculation() {

    $.ajax({
        type: "Get",
        url: "Controller.ashx?action=InitiateCirculation&documentId=" + document.getElementById("selectedForm").value,
        contentType: false,
        processData: false,
        success: function (result) {
            document.getElementById("Contents").innerHTML = result;
            alert("loaded");
            var dropbox = document.getElementById("dropbox");

            var cont = document.getElementById("condiv");
            var txt = $("#condiv").text();
            dropbox.addEventListener("dragenter", dragEnter, false);
            dropbox.addEventListener("dragexit", dragExit, false);
            dropbox.addEventListener("dragover", dragOver, false);
            dropbox.addEventListener("drop", drop, false);
            cont.addEventListener("dragenter", dragEnterr, false);
            alert("end");
          
        },
        error: function (xhr, err) {
            alert("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
            alert("responseText: " + xhr.responseText);
            console.log(xhr.responseText);
        }
    });   
    
}

function OpenFileUpload() {
    $('#myfile').click();   
}

function dragEnterr(evt) {
    
    $("#dropbox").show();
    evt.stopPropagation();
    evt.preventDefault();
}

function dragEnter(evt) {
    evt.stopPropagation();
    evt.preventDefault();
}

function dragExit(evt) {

    evt.stopPropagation();
    evt.preventDefault();

}

function dragOver(evt) {


    evt.stopPropagation();
    evt.preventDefault();
}

function drop(evt) {

    $("#dropbox").hide();
    evt.stopPropagation();
    evt.preventDefault();

    var files = evt.dataTransfer.files;
    var count = files.length;
    
    // Only call the handler if 1 or more files was dropped.
   // if (count > 0)
    //    handleFiles(files);
    $("#abc").show();
//
    for (var x = 0; x < count; x++) {
                var item = document.createElement("li");
                item.setAttribute('style', 'list-style-type: none');
                var c = document.createElement("input");
                c.setAttribute('type', 'checkbox');
                c.setAttribute('checked', 'checked');
                item.appendChild(c);
                var t = document.createTextNode(files[x].name);
    
                item.appendChild(t);
                document.getElementById('list_files').appendChild(item);

                //loading the array
                file_collection[index] = new Array(2);
                file_collection[index][0] = files[x].name;
                file_collection[index][1] = files[x];
                index++;
    }
 
}


function handleFiles(files) {

    alert(files.length);
    var file = files[0];

    document.getElementById("droplabel").innerHTML = "Processing " + file.name;

    var reader = new FileReader();

    // init the reader event handlers
    reader.onprogress = handleReaderProgress;
    reader.onloadend = handleReaderLoadEnd;

    // begin the read operation
    reader.readAsDataURL(file);  
}

function handleReaderProgress(evt) {
    if (evt.lengthComputable) {
        var loaded = (evt.loaded / evt.total);

        $("#progressbar").progressbar({ value: loaded * 100 });
    }
}

function handleReaderLoadEnd(evt) {
    $("#progressbar").progressbar({ value: 100 });

    var img = document.getElementById("preview");
    img.src = evt.target.result;
}
/*
function LoadViewCirculationDetails(cirId) {
    alert(cirId);
}*/

